/*
 * @Descripttion:
 * @Author: xiaodong
 * @Date: 2020-12-16 20:39:17
 * @LastEditTime: 2021-02-22 15:37:35
 * @FilePath: \cloud-monitor-server\src\app.js
 */
import "@babel/polyfill";

import path from "path";
import express from "express";
import _ from "lodash";
import router from "~/src/routes/index";
import appConfig from "~/src/configs/app";
import cookieParser from "cookie-parser";
import bodyParser from "body-parser";
import cors from "cors";
import Logger from "~/src/library/logger";

import Alert from "~/src/library/utils/modules/alert";
import WatchIdList from "~/src/configs/alarm";
import PrivilegeChecker from "~/src/middlewares/privilege";
import ejs from "ejs";

const startup = () => {
  const app = express();
  // 设置存放模板引擎目录
  app.set("views", path.join(__dirname, "../public"));
  // 设置模板引擎为ejs
  // app.set('view engine', 'ejs')
  app.engine("html", ejs.renderFile);
  app.set("view engine", "html");

  // 设置body-parser
  app.use(bodyParser.urlencoded({ extended: false }));

  // 解析json请求
  app.use(bodyParser.json({ extended: true }));

  // 解析text/plan请求
  app.use(bodyParser.text());

  // 设置cookie-parse
  app.use(cookieParser());

  // 支持跨域
  app.use(cors());

  // 将用户信息&项目信息补充到req中(在router内进行权限检测)
  app.use(PrivilegeChecker.appendUserInfo);
  app.use(PrivilegeChecker.appendProjectInfo);

  // app.use(async (req, res, next) => {

  //   await next();
  // });
  // 添加接口路径
  app.use("/", async (req, res, next) => {
    let path = req.path;
    if (
      _.endsWith(path, ".png") //上报的已图片返回
    ) {
      res.setHeader("Content-Type", "image/png");
    }
    // // 只对以 /api & /report&/project/${projectId}/api 路径开头的接口进行响应
    // let projectApiReg = /^\/project\/\d+\/api/i;
    if (
      _.startsWith(path, "/server") //http://localhost:3000
    ) {
      return router(req, res, next);
    } else {
      next();
    }
  });
  /* 添加静态路径 */
  app.use(express.static(path.join(__dirname, "../public")));
  // 支持前端History模式 => https://router.vuejs.org/zh/guide/essentials/history-mode.html#后端配置例子
  // 将所有404页面均返回index.html
  app.use("*", (req, res) => {
    res.render("index");
  });

  app.listen(appConfig.port, function () {
    Logger.log(`${appConfig.name} listening on port ${appConfig.port}`);
  });
};
startup();

process.on("uncaughtException", function (err) {
  Logger.error(err + ":服务器重新启动，启动时间：" + new Date().toString());
  Alert.sendMessage(
    WatchIdList.WATCH_UCID_LIST_DEFAULT,
    `[云监控]服务器重新启动, 原因: ${err}, 启动时间：${new Date().toString()}`
  );
  startup();
});
